import request from '@/utils/request'
import { encrypt } from '@/utils/encryption'
import { getServer, getUsername, getInternalServer, resolveHost, resolveInternalHost, getUserAuth } from '@/utils/auth'

export function loginByUsername(username, password, server) {
  const encryptPassword = encrypt(username, password)
  let host = getServer()
  let internalHost = getInternalServer()
  if (server) {
    host = resolveHost(server)
    internalHost = resolveInternalHost(server)
  }

  const data = {
    'username': username,
    'password': encryptPassword,
    'host': internalHost
  }
  return request({
    url: host + '/validateuser',
    method: 'post',
    data
  })
}

export function offlineLoginByUsername(username, password) {
  return new Promise((resolve, reject) => {
    const storedPassword = getUserAuth(username) || ''

    if (storedPassword === '') {
      reject(new Error('该用户还未登陆过，请在在线状态下登陆一次！'))
    } else {
      if (storedPassword !== password) {
        reject(new Error('用户密码错误！'))
      } else {
        resolve({ headers: { token: '0000000000' }})
      }
    }
  })
}

export function logout() {
  return request({
    url: '/login/logout',
    method: 'post'
  })
}

export function getUserInfo(token) {
  return new Promise((resolve, reject) => {
    const adminRoles = ['admin']
    const response = {
      data: {
        avatar: '',
        introduction: getUsername(),
        name: getUsername(),
        roles: adminRoles
      }
    }
    resolve(response)
  })
}
